package  
{
	import org.flixel.*;
	/**
	 * ...
	 * @author jfields
	 */
	public class Turret extends FlxSprite
	{
		[Embed (source = "../data/turret.png")] private var img_turret:Class;
		
		public var offx:int;
		public var offy:int;
		public var pattern:BulletPattern;
		public var bulletType:int;
		public var fireAngle:Number;
		public var fireSpeed:Number;
		public var refire:Number;
		
		public var refireTimer:Number = 0;
		
		public var behaviors:Array;
		public var behaviorTime:Number = 0;
		public var absolute:Boolean = false;
		
		public function Turret(offx:int, offy:int, pattern:BulletPattern, type:int, angle:Number = 0, speed:Number = 100, refire:Number = 0.5, absolute:Boolean = false) 
		{
			this.offx = offx;
			this.offy = offy;
			this.pattern = pattern;
			bulletType = type;
			fireAngle = angle;
			fireSpeed = speed;
			this.refire = refire;
			super(0, 0, img_turret);
			offset.x = 4;
			offset.y = 4;
			width = 0; height = 0;
			this.absolute = absolute;
			
			// Default to being disabled, the boss will enable us as he needs
			exists = false;
			visible = false;
			
			behaviors = new Array();
		}
		
		public function spawn():void
		{
			if (!exists)
			{
				exists = true;
				refireTimer = 0;
				//behaviorTime = 0;
			}
		}
		
		public function addBehavior(behavior:TurretBehavior):void
		{
			behaviors.push(behavior);
		}
		
		override public function update():void 
		{
			behaviorTime += FlxG.elapsed;
			for (var i:int = 0; i < behaviors.length; i++)
			{
				behaviors[i].onUpdate(this);
			}
			super.update();
			if (absolute)
			{
				x = GameState.FIELDLEFT + GameState.FIELDWIDTH / 2 + offx;
				y = FlxG.height / 2 + offy;
			}
			else
			{
				x = GameState.ref.boss.x + GameState.ref.boss.width / 2 + offx;
				y = GameState.ref.boss.y + GameState.ref.boss.height / 2 + offy;
			}
			refireTimer -= FlxG.elapsed;
			if (refireTimer < 0)
			{
				fireBullet();
				refireTimer = refire;
			}
		}
		
		public function fireBullet():void
		{
			var rads:Number = fireAngle * 3.14159 / 180;
			var vx:Number = Math.cos(rads) * fireSpeed;
			var vy:Number = Math.sin(rads) * fireSpeed;
			GameState.ref.makeBullet(bulletType, x, y, vx, vy, pattern);
		}
	}

}